const app = getApp()
import { getProjectInfo, getProjectSpaceCategory, getProjectMaterial, deleteProjectMaterial, getMaterialBook, postDeleteMaterialBook, intoMaterialBook, getProjectMemberList, inviteProjectMember, deleteProjectMember, getPdfByCategory } from '../../../../api/index'
import { formatTimeTwo } from '../../../../utils/util'

Page({
  data: {
    role: '',
    tabActive: 'detail',
    projectId: '',
    projectType: '',
    activeSpace: '',
    detail: {},
    spaceList: [],
    materialList: [],
    spaceTabH: 0,
    safeBottom: 0,
    sections: [],
    allCount: 0,
    activeCate: 0,
    refresher: false,
    categorys: [
      { label: '全部空间', value: 0, key: 'allCount', allCount: 0 },
      { label: '主材表', value: 1, key: 'mainCount', mainCount: 0 },
      { label: '洁具表', value: 2, key: 'sanitaryCount', sanitaryCount: 0 },
      { label: '五金表', value: 3, key: 'hardwareCount', hardwareCount: 0 },
      { label: '开关面板表', value: 4, key: 'buttonCount', buttonCount: 0 },
      { label: '电器', value: 5, key: 'electricalCount', electricalCount: 0 },
      { label: '灯具', value: 6, key: 'lightingCount', lightingCount: 0 }
    ],
    bookList: [],
    searchName: '',
    memberList: [],
    searchTabH: 0,
    showMemberPop: false
  },
  editMaterial ({ currentTarget: { dataset: { item } } }) {
    wx.$nav.navigateTo(`/pages/account/project/editMaterial/index?projectId=${this.data.projectId}&id=${item.id}&spaceId=${this.data.activeSpace}`)
  },
  editMember ({ currentTarget: { dataset: { item } } }) {
    if (parseInt(item.role) !== 1) wx.$nav.navigateTo(`/pages/account/project/editMember/index?projectId=${this.data.projectId}&userId=${item.userId}&role=${this.data.role}`)
  },
  addMember () {
    this.setData({ showMemberPop: true })
  },
  closeMemberPop () {
    this.setData({ showMemberPop: false })
  },
  search ({ detail }) {
    this.setData({ searchName: detail })
    this.getMember()
  },
  async download ({ currentTarget: { dataset: { item } } }) {
    try {
      const { ResultSet } = await getPdfByCategory({ bookNo: item.bookNo, category: this.data.activeCate })
      const { errMsg } = await wx.$pro.setClipboardData({ data: ResultSet.userData.fileUrl })
      if (errMsg === 'setClipboardData:ok') {
        wx.showToast({ title: 'PDF文件地址已复制，请到浏览器中下载并查看！', icon: 'none' })
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async confirmMember ({ detail }) {
    try {
      let ids = detail.map(item => { return item.userId })
      await inviteProjectMember({ projectId: this.data.projectId, userIdList: ids })
      wx.showToast({ title: '邀请成功！', icon: 'none' })
      this.setData({ showMemberPop: false })
      this.getRequest()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async delMember ({ currentTarget: { dataset: { item } } }) {
    try {
      const { confirm } = await wx.$pro.showModal({ title: '提示', content: '确定要删除该成员吗？' })
      if (confirm) {
        await deleteProjectMember({ projectId: this.data.projectId, memberUserId: item.userId })
        wx.showToast({ title: '删除成功！', icon: 'none' })
        this.getRequest()
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async delMaterial () {
    try {
      if (!this.data.sections.length) {
        wx.showToast({ title: '请先选择要删除的数据！', icon: 'none' })
        return
      }
      const { confirm } = await wx.$pro.showModal({ title: '提示', content: '确定要删除选择的选材吗？' })
      if (confirm) {
        let ids = this.data.sections.map(item => { return item.id })
        await deleteProjectMaterial({ projectId: this.data.projectId, projectMaterialIds: ids.join(',') })
        wx.showToast({ title: '删除成功！', icon: 'none' })
        this.getSpace()
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async delBook () {
    try {
      if (!this.data.sections.length) {
        wx.showToast({ title: '请先选择要删除的数据！', icon: 'none' })
        return
      }
      const { confirm } = await wx.$pro.showModal({ title: '提示', content: '确定要删除选择的材料册吗？' })
      if (confirm) {
        let ids = this.data.sections.map(item => { return item.bookNo })
        await postDeleteMaterialBook({ projectId: this.data.projectId, bookNos: ids })
        wx.showToast({ title: '删除成功！', icon: 'none' })
        this.getMaterialBook()
      }
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  generateBook () {
    if (!this.data.sections.length) {
      wx.showToast({ title: '请先选择材料！', icon: 'none' })
      return
    }
    let ids = this.data.sections.map(item => { return item.id })
    wx.$nav.navigateTo(`/pages/account/project/books/index?ids=${ids.join(',')}&projectId=${this.data.projectId}`)
  },
  selectSpace ({ currentTarget: { dataset: { item } } }) {
    this.setData({ activeSpace: item && item.spaceId ? item.spaceId : '' })
    this.getMaterials()
  },
  cancelAll () {
    this.data.materialList.forEach(item => {
      item.isChecked = false
    })
    this.data.bookList.forEach(item => {
      item.isChecked = false
    })
    this.setData({ materialList: this.data.materialList, bookList: this.data.bookList, sections: [] })
  },
  selectRadio ({ currentTarget: { dataset: { item, index } } }) {
    let key = `materialList[${index}].isChecked`
    this.setData({ [key]: !item.isChecked })
    let sections = this.data.materialList.filter(item => item.isChecked)
    this.setData({ sections: sections })
  },
  selectBookRadio ({ currentTarget: { dataset: { item, index } } }) {
    let key = `bookList[${index}].isChecked`
    this.setData({ [key]: !item.isChecked })
    let sections = this.data.bookList.filter(item => item.isChecked)
    this.setData({ sections: sections })
  },
  selectCate ({ currentTarget: { dataset: { item } } }) {
    this.setData({ activeCate: item.value })
    this.getMaterialBook()
  },
  addSpace () {
    wx.$nav.navigateTo(`/pages/account/project/spaceManage/index?id=${this.data.projectId}`)
  },
  changeTab ({ currentTarget: { dataset: { value } } }) {
    this.setData({ tabActive: value })
    this.getRequest()
    // if (value === 'detail') this.getCaseList()
    // else this.getFolderList()
  },
  async confirmJoin () {
    try {
      if (!this.data.sections.length) {
        wx.showToast({ title: '请先选择材料册！', icon: 'none' })
        return
      }
      let ids = this.data.sections.map(item => { return item.bookNo })
      await intoMaterialBook({ projectId: this.data.projectId, bookNos: ids })
      wx.showToast({ title: '入册成功！', icon: 'none' })
      this.getMaterialBook()
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async onRefresh () {
    await this.getRequest()
    this.setData({ refresher: false })
  },
  getRequest () {
    if (this.data.tabActive === 'detail') {
      this.getDetail()
    } else if (this.data.tabActive === 'material') {
      let query = this.createSelectorQuery()
      query.select('.space-list').boundingClientRect(rect=>{
        let height = rect.height
        this.setData({ spaceTabH: height + 10 })
      }).exec()
      this.getSpace()
    } else if (this.data.tabActive === 'book') {
      let query = this.createSelectorQuery()
      query.select('.space-list').boundingClientRect(rect=>{
        let height = rect.height
        this.setData({ spaceTabH: height + 10 })
      }).exec()
      this.getMaterialBook()
    } else if (this.data.tabActive === 'member') {
      let query = this.createSelectorQuery()
      query.select('.search').boundingClientRect(rect=>{
        let height = rect.height
        this.setData({ searchTabH: height + 10 })
      }).exec()
      this.getMember()
    }
  },
  async getMember () {
    try {
      wx.showLoading({ title: '加载中...', mask: true })
      const { ResultSet } = await getProjectMemberList({ searchName: this.data.searchName, projectId: this.data.projectId })
      this.setData({ memberList: ResultSet.userData.data })
      wx.hideLoading()
    } catch (err) {
      wx.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getMaterialBook () {
    try {
      wx.showLoading({ title: '加载中...', mask: true })
      const { ResultSet } = await getMaterialBook({ category: this.data.activeCate, projectId: this.data.projectId })
      ResultSet.userData.materialBooks.forEach(item => {
        item.isChecked = false
      })
      this.data.categorys.forEach(item => {
        item[item.key] = ResultSet.userData[item.key]
      })
      this.setData({ bookList: ResultSet.userData.materialBooks, categorys: this.data.categorys })
      wx.hideLoading()
    } catch (err) {
      wx.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getDetail () {
    try {
      const { ResultSet } = await getProjectInfo({ projectId: this.data.projectId })
      ResultSet.userData.projectInfo.projectDate = formatTimeTwo(ResultSet.userData.projectInfo.projectDate, 'Y-M')
      this.setData({ detail: ResultSet.userData.projectInfo, role: ResultSet.userData.role })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getSpace () {
    try {
      const { ResultSet } = await getProjectSpaceCategory({ projectId: this.data.projectId })
      let allCount = ResultSet.userData.projectSpace.map(item => { return item.count }).reduce((n,m) => n + m)
      this.setData({ spaceList: ResultSet.userData.projectSpace, allCount: allCount })
      this.getMaterials()
    } catch (err) {
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getMaterials () {
    try {
      wx.showLoading({ title: '加载中...', mask: true })
      let query = {
        projectId: this.data.projectId
      }
      if (this.data.activeSpace) query.spaceId = this.data.activeSpace
      const { ResultSet } = await getProjectMaterial({ ...query })
      ResultSet.userData.data.forEach(item => {
        item.isChecked = false
      })
      this.setData({ materialList: ResultSet.userData.data, sections: [] })
      wx.hideLoading()
    } catch (err) {
      wx.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ id }) {
    const { screenHeight, safeArea: { bottom } } = wx.$pro.getSystemInfoSync()
    this.setData({ safeBottom: screenHeight - bottom, projectId: id })
    console.log(this.data.projectId)
    // this.getRequest()
  },
  onShow () {
    this.getRequest()
  }
})